package ua.amsoft.brelok.manager;

import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

import org.apache.commons.validator.routines.UrlValidator;

import ua.amsoft.brelok.task.CheckServerReachableTask;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.util.Log;

public class ConnectionManager {
    
    private static final String TAG = "ConnectionManager";
    
    /**
     * Checks network connection state
     * 
     * @param context
     * @return boolean is network connected
     */
    public boolean isNetworkConnected(final Context context) {
        final ConnectivityManager conMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        
        final State mobileState = conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
        
        final State wifiState = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        
        if ((NetworkInfo.State.CONNECTED.equals(wifiState))
                || (NetworkInfo.State.CONNECTED.equals(mobileState))) {
            return true;
            
        } else if ((NetworkInfo.State.DISCONNECTED.equals(wifiState))
                || (NetworkInfo.State.DISCONNECTED.equals(mobileState))) {
            return false;
        }
        return false;
    }
    
    public boolean isServerReachable(final String url) throws IOException {
        try {
            final CheckServerReachableTask checkServerReachableTask = new CheckServerReachableTask();
            final String parsedUrl = parseUrl(url);
            if (UrlValidator.getInstance().isValid(parsedUrl)) {
                return checkServerReachableTask.execute(parsedUrl).get();
            }
        } catch (final InterruptedException e) {
            Log.e(ConnectionManager.TAG, e.getLocalizedMessage());
            return false;
        } catch (final ExecutionException e) {
            Log.e(ConnectionManager.TAG, e.getLocalizedMessage());
            return false;
        }
        return false;
    }
    
    private String parseUrl(final String urlString) {
        final StringBuilder builder = new StringBuilder();
        try {
            final URL url = new URL(urlString);
            builder.append(url.toURI().getScheme());
            builder.append("://");
            builder.append(url.toURI().getAuthority());
        } catch (final Exception e) {
            Log.e(ConnectionManager.TAG, "URL parsing failed: " + e.getLocalizedMessage());
        }
        return builder.toString();
    }
    
}
